package com.lb.bs.client.util;

import java.lang.reflect.Field;

/**
 * program: LB-BS-Client
 * author: bsworld.xie
 * create: 2019-11-27 20:49
 * description:
 */
public class FieldUtil {

    public static Object transform(Field field, Object value) {

        if (field == null) {
            return value;
        }
        // process
        String typeName = field.getType().getName();
        typeName = typeName.toLowerCase();
        if (!(value instanceof String)) {
            value = "";
        }
        String dataValue = (String) value;
        if (typeName.equals("int")) {

            if (dataValue.equals("")) {
                dataValue = "0";
            }
            return Integer.valueOf(dataValue);
        } else if (typeName.equals("java.lang.integer")) {
            return StringUtils.isEmpty(dataValue) ? null : Integer.valueOf(dataValue);

        } else if (typeName.equals("long")) {
            if (dataValue.equals("")) {
                dataValue = "0";
            }
            return Long.valueOf(dataValue);

        } else if (typeName.equals("java.lang.long")) {
            return StringUtils.isEmpty(dataValue) ? null : Long.valueOf(dataValue);
        } else if (typeName.equals("boolean")) {
            if (dataValue.equals("")) {
                dataValue = "false";
            }
            return Boolean.valueOf(dataValue);

        } else if (typeName.equals("java.lang.boolean")) {

            return StringUtils.isEmpty(dataValue) ? null : Boolean.valueOf(dataValue);

        } else if (typeName.equals("double")) {

            if (dataValue.equals("")) {
                dataValue = "0.0";
            }

            return Double.valueOf(dataValue);
        } else if (typeName.equals("java.lang.double")) {

            return StringUtils.isEmpty(dataValue) ? null : Double.valueOf(dataValue);
        } else if (typeName.equals("float")) {
            if (dataValue.equals("")) {
                dataValue = "0.0";
            }
            return Float.valueOf(dataValue);
        } else if (typeName.equals("java.lang.float")) {
            return StringUtils.isEmpty(dataValue) ? null : Float.valueOf(dataValue);
        }
        return value;
    }


    public static String transform2String(Object value) {
        if (!(value instanceof String)) {
            value = "";
        }
        return (String) value;
    }

}
